<?php


class CHtml2PdfContext
{
	private $variables = array();

	public function __construct()
	{
		$this->variables = array();
	}

	public function put($name, $variable)
	{
		if (isset($this->variables[$name]))
		throw new CHtml2PdfDuplicateVariableException($name);
		$this->variables[$name] = $variable;
	}
	
	public function keySet() {
		return array_keys($this->variables);
	}
	
	public function get($key) {
			return $this->variables[$key];
	}

	public function valueOf($string)
	{
		$paths = split("\.", $string);

		if (!isset($this->variables[$paths[0]]))
		{
			throw new CHtml2PdfParseException($paths[0], $string, "context variable");
		}
		
		$obj = $this->variables[$paths[0]];
		array_shift($paths);
		try {
			while (count($paths) > 0 && isset($obj))
			{
				$path = $paths[0];
				if (isset($obj))
				{
					eval ("\$obj = \$obj->".$path.";");
				}
				array_shift($paths);
			}
		}catch(Exception $ex){
			throw new CHtml2PdfParseException($paths[0], $string, "context variable");
		}

		return $obj;
	}
	
	public function __clone()
	{
		return new CHtml2PdfContext();
	}
}

define ('ERR_C2P_DUPLICATE_VAR', 1);
define ('ERR_C2P_PARSE', 1);

abstract class CHtml2PdfException extends Exception
{
	public function __construct ($message = "", $code = 0, $previous = NULL)
	{
		parent::__construct ($message, $code);
	}
}

class CHtml2PdfDuplicateVariableException extends CHtml2PdfException
{
	public function __construct ($var, $previous = NULL)
	{
		parent::__construct (sprintf('Try to insert duplicate variable %s in context.', $var), ERR_C2P_DUPLICATE_VAR, $previous);
	}
}

class CHtml2PdfParseException extends CHtml2PdfException
{
	public function __construct ($path, $string, $contextName, $previous = NULL)
	{
		parent::__construct (sprintf('Cannot parse %s. %s not found in %s', $string, $path, $contextName), ERR_C2P_PARSE, $previous);
	}
}

